'use client'
import { useParams } from 'next/navigation'
import { useEffect, useState } from 'react'

import { MessageItem } from '@/app/types/Chat'
import ChatButton from '@/components/chat/ChatButton'
import MessageBox from '@/components/chat/MessageBox'
import { createClient } from '@/utils/supabase/client'

const supabase = createClient()

export default function ThreadPage() {
  const { id } = useParams<{ id: string }>()

  const [messages, setMessages] = useState<MessageItem[]>([])

  useEffect(() => {
    const getMessages = async () => {
      const { data, error } = await supabase
        .from('messages')
        .select('*')
        .eq('thread_id', id)

      if (error) console.error(error)
      console.log('data')

      setMessages(data || [])
    }
    getMessages()
  }, [id])

  return (
    <div className="h-full flex flex-col px-4 py-8">
      <div className="flex-1 overflow-y-auto">
        {messages.map(message => (
          <MessageBox key={message.id} message={message} />
        ))}
      </div>
      <ChatButton threadId={id} />
    </div>
  )
}
